//
//  TPPhotoBrowserAnimation.m
//  美丽说图片浏览器
//
//  Created by 唐鹏 on 16/7/14.
//  Copyright © 2016年 tangpeng. All rights reserved.
//

#import "TPPhotoBrowserAnimation.h"
#import "TPHomeViewController.h"
#import "TPPhotoBrowserViewController.h"

@interface TPPhotoBrowserAnimation()

@end

@implementation TPPhotoBrowserAnimation

- (UIImageView *)dimisImageView{
    if (!_dimisImageView) {
        _dimisImageView = [[UIImageView alloc] init];
    }
    return _dimisImageView;
}

#pragma mark <UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning>

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext{
    return 0.5;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{
    if (self.isPresenting) {
        
        UIView *presentedView = [transitionContext viewForKey:UITransitionContextToViewKey];
        UIView *tempView = [transitionContext containerView];
        [tempView addSubview:self.imageView];
        
        tempView.backgroundColor = [UIColor blackColor];
        self.imageView.frame = self.startRect;
        
        CGFloat duration = [self transitionDuration:transitionContext];
        
        [UIView animateWithDuration:duration animations:^{
            self.imageView.frame = self.endRect;
          
        } completion:^(BOOL finished) {
            
            [tempView addSubview:presentedView];
            tempView.backgroundColor = [UIColor clearColor];
            [self.imageView removeFromSuperview];
            [transitionContext completeTransition:YES];
        }];
        
    }else{
        UIView *dismissView = [transitionContext viewForKey:UITransitionContextFromViewKey];
        UIView *tempView = [transitionContext containerView];
        [tempView addSubview:self.dimisImageView];
        CGFloat duration = [self transitionDuration:transitionContext];
        
        CGRect temtRect = CGRectMake(0, 64, 0, 0);
        dismissView.alpha = ([NSStringFromCGRect(self.startRect)isEqualToString: NSStringFromCGRect(temtRect)]) ? 1.0 : 0.0;
        
        [UIView animateWithDuration:duration animations:^{
            
            if ([NSStringFromCGRect(self.startRect) isEqualToString:NSStringFromCGRect(temtRect)]) {
                
                [self.dimisImageView removeFromSuperview];
                dismissView.alpha = 0;
                
            }else{
                
            self.dimisImageView.frame = self.startRect;
                [dismissView removeFromSuperview];
                
            }
        } completion:^(BOOL finished) {
            
            [transitionContext completeTransition:YES];
        }];
    }
    
}


@end
